import React, { useRef, useEffect } from "react";
import {
    Scene, WebGLRenderer, BoxGeometry, MeshNormalMaterial, Mesh,
    Matrix4, Vector3, PerspectiveCamera, Object3DEventMap, Light, DirectionalLight, MeshPhongMaterial,
} from 'three';
import "./css/ResponsiveDesign.css"

//Canvas自适应
const scene = new Scene();
const camera = new PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.copy(new Vector3(0, 0, 5));
camera.lookAt(new Vector3(0, 0, 0));

const renderer = new WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight, false);

const geometry = new BoxGeometry();
const material = new MeshPhongMaterial({ color: 0x44aa88 });

let cubeIndex = 0;
const cubeCreate = (x: number) => {
    const cube = new Mesh(geometry, material);
    cube.position.set(x, 0, 0);
    cube.name = cubeIndex++ + '';
    return cube;
};

const cubes = [-2, 0, 2].map((x) => cubeCreate(x));
scene.add(...cubes);

const color = 0xffffff;
const intensity = 1;
const light = new DirectionalLight(color, intensity);
light.position.set(2, 2, 2);
scene.add(light);

window.addEventListener("resize", function () {
    setRenderSize(renderer);
})


let isRender = 0;
function animate(isRender: number) {
    if (isRender != 0) return;

    cubes.map((cube) => {
        if (cube.name == '1') {
            cube.rotation.x -= 0.01;
            cube.rotation.y -= 0.01;
        } else {
            cube.rotation.x += 0.01;
            cube.rotation.y += 0.01;
        }
    })

    renderer.render(scene, camera);
    requestAnimationFrame(() => {
        animate(isRender);
    });
}

function setRenderSize(renderer: WebGLRenderer) {
    const { width, height, clientHeight, clientWidth } = renderer.domElement;

    if (width !== clientWidth || height !== clientHeight) {
        //如果为true会设置style的W/H
        renderer.setSize(clientWidth * devicePixelRatio, clientHeight * devicePixelRatio, false);
        camera.aspect = clientWidth / clientHeight;
        camera.updateProjectionMatrix();
    }
}


const RenderStructure = () => {
    const divRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        const { current } = divRef;
        if (current != null) {
            current.innerHTML = '';
            current.append(renderer.domElement);
        }
        animate(isRender);
        isRender++;
    }, []);
    return (
        <div ref={divRef}></div>
    );
};

export default RenderStructure;